//
//  DeviceChartVC.m
//  efairy
//  设备图标日志
//  Created by 李锋 on 2019/1/21.
//  Copyright © 2019年 East. All rights reserved.
//

#import "DeviceChartVC.h"
#import "EFAModel.h"
#import "YYModel.h"
#import "MJRefresh.h"
#import "ApiManager.h"
#import "GlobalHeader.h"
#import "DevciceChartCell.h"
#import <UIScrollView+EmptyDataSet.h>
#import "XJTimePickView.h"

@interface DeviceChartVC ()<UITableViewDelegate,UITableViewDataSource,DZNEmptyDataSetDelegate, DZNEmptyDataSetSource>
@property (strong,nonatomic) UIView *dateView;
@property (strong,nonatomic) UILabel *dateTitle;
@property (strong,nonatomic) UILabel *startDateLabel;
@property (strong,nonatomic) UILabel *endDateLabel;
@property (strong,nonatomic) UIView *dateContentView;
@property (strong,nonatomic) UIView *statrDateView;
@property (strong,nonatomic) UIView *endDateView;
@property (strong,nonatomic) UIButton *cancel;
@property (strong,nonatomic) UIButton *confirm;
@property (strong,  nonatomic) UITableView *tableView;
@property (nonatomic, strong) MJRefreshComponent *refreshViewComponent;
@property (strong, nonatomic) EFADeviceInfoModel *deviceInfo;
@property (strong,nonatomic) XJTimePickView *startTimePickView;
@property (strong,nonatomic) XJTimePickView *endTimePickView;
@property (strong,nonatomic) NSString *startDate;
@property (strong,nonatomic) NSString *endDate;
@property (assign,nonatomic) BOOL isEndTime;
@end

@implementation DeviceChartVC

- (void)viewDidLoad {
    [super viewDidLoad];
    [self initNavigationBar];
    [self setupView];
    [self setupDateChooseView];
    
    
}
-(BOOL)hidesBottomBarWhenPushed{
    return YES;
}

- (void)initNavigationBar {
    self.navigationItem.title = @"设备图表";
}

-(void)setupView{
    NSDate *date=[NSDate date];
    NSDateFormatter *format1=[[NSDateFormatter alloc] init];
    [format1 setDateFormat:@"yyyy-MM-dd"];
    NSString *dateStr;
    dateStr=[format1 stringFromDate:date];
    _startDate = dateStr;
    _endDate =dateStr;
    float  navigationbar = self.navigationController.navigationBar.frame.size.height;
    _dateView = [[UIView alloc]initWithFrame:CGRectMake(0, statusBarHeight+navigationbar, SCREEN_WIDTH, 44)];
    _dateView.backgroundColor = [UIColor whiteColor];
    _dateTitle = [[UILabel alloc]init];
    _dateTitle.font = [UIFont systemFontOfSize:14.f];
    _dateTitle.textColor= ColorFromRGB(0x666666);
    _dateTitle.text = @"时间选择";
    
    _startDateLabel = [[UILabel alloc]init];
    _startDateLabel.font = [UIFont systemFontOfSize:14.f];
    _startDateLabel.textColor= ColorFromRGB(0x333333);
    _startDateLabel.text =dateStr;
    
    
    UIView *line  = [[UIView alloc]init];
    line.backgroundColor = ColorFromRGB(0xcccccc);
    
    _endDateLabel = [[UILabel alloc]init];
    _endDateLabel.font = [UIFont systemFontOfSize:14.f];
    _endDateLabel.textColor= ColorFromRGB(0x333333);
    _endDateLabel.text =dateStr;
   
    
    
    UIImageView  *rightArrow = [[UIImageView alloc]init];
    rightArrow.image = [UIImage imageNamed:@"icon_right_arrow"];
    
    
    UITapGestureRecognizer *tapDateView = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(showDateChose:)];
    [_dateView addGestureRecognizer:tapDateView];
    
    [_dateView sd_addSubviews:@[_dateTitle,_startDateLabel,line,_endDateLabel,rightArrow]];
    
    _dateTitle.sd_layout.widthIs(58).heightIs(14)
    .leftSpaceToView(_dateView, 16)
    .topSpaceToView(_dateView,15);
    
    _startDateLabel.sd_layout.widthIs(80).heightIs(14)
    .leftSpaceToView(_dateTitle, 10)
    .topSpaceToView(_dateView,15);
    
    line.sd_layout.widthIs(20).heightIs(2)
    .leftSpaceToView(_startDateLabel, 22)
    .topSpaceToView(_dateView,21);
    
    _endDateLabel.sd_layout.widthIs(80).heightIs(14)
    .leftSpaceToView(line, 22)
    .topSpaceToView(_dateView,15);
    
    
    rightArrow.sd_layout.widthIs(8).heightIs(13)
    .rightSpaceToView(_dateView, 16)
    .topSpaceToView(_dateView,15.5);
    
    
    self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, statusBarHeight+navigationbar+44, SCREEN_WIDTH, SCREEN_HEIGHT-statusBarHeight-navigationbar-44)];
    self.tableView.backgroundColor = BG;
//    self.tableView.rowHeight = UITableViewAutomaticDimension;
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.emptyDataSetDelegate = self;
    self.tableView.emptyDataSetSource = self;

    //多余分割线不显示
    self.tableView.tableFooterView = [[UIView alloc] initWithFrame:CGRectZero];
    [self.view sd_addSubviews:@[_dateView,self.tableView ]];
    self.automaticallyAdjustsScrollViewInsets = NO;
    
    
    
    __weak typeof(self) weakSelf = self;
    //..下拉刷新
    self.tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        weakSelf.refreshViewComponent = weakSelf.tableView.mj_header;
        [weakSelf requestDeviceChart];
    }];
    
    // 马上进入刷新状态
    [self.tableView.mj_header beginRefreshing];
}


-(void)setupDateChooseView{
    
     UIWindow *wd = [[UIApplication sharedApplication].windows lastObject];
    _dateContentView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, SCREEN_HEIGHT)];
    //只设置黑白背景色,这种设置方式不会导致子view也跟随透明
    _dateContentView.backgroundColor =  [UIColor colorWithWhite:0.f alpha:0.5];
    
    
    _statrDateView = [[UIView alloc] initWithFrame:CGRectMake(20, 150, SCREEN_WIDTH-40, SCREEN_HEIGHT-300)];
    _statrDateView.backgroundColor =  [UIColor whiteColor];
    
    UILabel *startDateTitle = [[UILabel alloc]init];
    startDateTitle.font = [UIFont boldSystemFontOfSize:17.f];
    startDateTitle.textColor = ColorFromRGB(0x3F3F3F);
    startDateTitle.textAlignment = NSTextAlignmentCenter;
    startDateTitle.text = @"起始时间";
    
    UILabel *endDateTitle = [[UILabel alloc]init];
    endDateTitle.font = [UIFont boldSystemFontOfSize:17.f];
    endDateTitle.textColor = ColorFromRGB(0x3F3F3F);
    endDateTitle.textAlignment = NSTextAlignmentCenter;
    endDateTitle.text = @"结束时间";
    
    _startTimePickView = [self statrTimePickView];
    _endTimePickView = [self endTimePickView];
    
    _cancel = [[UIButton alloc]init];
    [_cancel setTitle:@"取消" forState:UIControlStateNormal];
    [_cancel setTitleColor:ColorFromRGB(0x999999) forState:UIControlStateNormal];
    _cancel.titleLabel.font = [UIFont boldSystemFontOfSize:16.f];
     [_cancel addTarget:self action:@selector(cancelChooseDate:) forControlEvents:UIControlEventTouchUpInside];
    
    
    UIView *vline = [[UIView alloc]init];
    vline.backgroundColor = ColorFromRGB(0xe5e5e5);
    
    UIView *hline = [[UIView alloc]init];
    hline.backgroundColor = ColorFromRGB(0xe5e5e5);

    
    _confirm = [[UIButton alloc]init];
    [_confirm setTitle:@"确定" forState:UIControlStateNormal];
    [_confirm setTitleColor:ColorFromRGB(0x282449) forState:UIControlStateNormal];
    _confirm.titleLabel.font = [UIFont boldSystemFontOfSize:16.f];
    [_confirm addTarget:self action:@selector(confirmChooseDate:) forControlEvents:UIControlEventTouchUpInside];
    
    [_statrDateView sd_addSubviews:@[startDateTitle,_startTimePickView,endDateTitle,_endTimePickView,hline,_cancel,vline,_confirm]];
    
    startDateTitle.sd_layout.widthIs(SCREEN_WIDTH-40)
    .heightIs(40)
    .topSpaceToView(_statrDateView, 0);
    
    _startTimePickView.sd_layout.widthIs(SCREEN_WIDTH-40)
    .heightIs((SCREEN_HEIGHT-425)/2)
    .topSpaceToView(startDateTitle, 0);
    
    endDateTitle.sd_layout.widthIs(SCREEN_WIDTH-40)
    .heightIs(40)
    .topSpaceToView(_startTimePickView, 20);
    
    _endTimePickView.sd_layout.widthIs(SCREEN_WIDTH-40)
    .heightIs((SCREEN_HEIGHT-425)/2)
    .topSpaceToView(endDateTitle, 0);
    
    hline.sd_layout.heightIs(1)
    .leftSpaceToView(_statrDateView, 0)
    .rightSpaceToView(_statrDateView,0)
    .bottomSpaceToView(_statrDateView, 44);
    
    _cancel.sd_layout.widthIs((SCREEN_WIDTH-40)/2-0.5).heightIs(44)
    .bottomSpaceToView(_statrDateView, 0);
    
    vline.sd_layout.widthIs(1).heightIs(20)
    .bottomSpaceToView(_statrDateView, 14)
    .leftSpaceToView(_cancel, 0);
    
    _confirm.sd_layout.widthIs((SCREEN_WIDTH-40)/2-0.5).heightIs(44)
    .leftSpaceToView(vline, 0)
    .bottomSpaceToView(_statrDateView, 0);
    
    [_dateContentView addSubview:_statrDateView];
    [wd addSubview:_dateContentView];
    _dateContentView.hidden = YES;
  
    [self setDefaultsDate];
    
}

- (XJTimePickView *)statrTimePickView{
    if (!_startTimePickView) {
        _startTimePickView = [[XJTimePickView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-40, (SCREEN_HEIGHT-425)/2)];
         __weak typeof(self) weakSelf = self;
        _startTimePickView.calendarChangeBlock = ^(NSString *changeTime) {
            weakSelf.startDate = changeTime;
        };
    }
    return _startTimePickView;
}

- (XJTimePickView *)endTimePickView{
    if (!_endTimePickView) {
        __weak typeof(self) weakSelf = self;
        _endTimePickView = [[XJTimePickView alloc]initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH-40, (SCREEN_HEIGHT-425)/2)];
        _endTimePickView.calendarChangeBlock = ^(NSString *changeTime) {
            weakSelf.endDate = changeTime;
        };
    }
    return _endTimePickView;
}

-(void)showDateChose:(id)tap{
    NSLog(@"showDateChoses执行了");
    _dateContentView.hidden = NO;
}


-(void)cancelChooseDate:(id)tap{
     _dateContentView.hidden = YES;
}

-(void)confirmChooseDate:(id)tap{
    _dateContentView.hidden = YES;
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    [dateFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:8]];//解决8小时时间差问题
    NSDate *sDate = [dateFormatter dateFromString:_startDate];
    NSDate *eDate = [dateFormatter dateFromString:_endDate];
    NSComparisonResult result =[sDate compare:eDate];
    //利用NSCalendar比较日期的差异
    NSCalendar* calendar = [NSCalendar currentCalendar];
    /**
     * 要比较的时间单位,常用如下,可以同时传：
     *    NSCalendarUnitDay : 天
     *    NSCalendarUnitYear : 年
     *    NSCalendarUnitMonth : 月
     *    NSCalendarUnitHour : 时
     *    NSCalendarUnitMinute : 分
     *    NSCalendarUnitSecond : 秒
     */
    NSCalendarUnit unit = NSCalendarUnitDay;//只比较天数差异
    //比较的结果是NSDateComponents类对象
    NSDateComponents *delta = [calendar components:unit fromDate:sDate toDate:eDate options:0];
    //打印
//    NSLog(@"%@",delta);
    //获取其中的"天"
//    NSLog(@"%ld",delta.day);
    switch (result) {
        case NSOrderedAscending:
            if(delta.day >= 7){
                [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"最多只能查询7天的数据"];
            }else{
                _startDateLabel.text = _startDate;
                _endDateLabel.text  = _endDate;
                [self requestDeviceChart];
            }
            break;
        case NSOrderedDescending:
            [MBProgressHUD showPromptWithAutoHideInView:self.view message:@"起始时间不能大于结束时间"];
            break;
        case NSOrderedSame:
            _startDateLabel.text = _startDate;
            _endDateLabel.text  = _endDate;
            [self requestDeviceChart];
            break;
        default:
            break;
    }
  
    
}

#pragma mark - DZNEmptyDataSetSource
- (NSAttributedString *)descriptionForEmptyDataSet:(UIScrollView *)scrollView {
    NSDictionary *dic = @{NSFontAttributeName : [UIFont systemFontOfSize:14.0]};
    return [[NSAttributedString alloc] initWithString:@"当前没有信息" attributes:dic];
}

- (UIImage *)imageForEmptyDataSet:(UIScrollView *)scrollView {
    //    return [KABDefaultVarModel sharedInstance].bitmapDefaultImg;
    return nil;
}

//- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView {
//    return -100.0;
//}
#pragma mark - DZNEmptyDataSetDelegate
- (BOOL)emptyDataSetShouldAllowScroll:(UIScrollView *)scrollView {
    return YES;
}

//- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
//    return 1;
//}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if(self.deviceInfo && self.deviceInfo.streamPtCidArray.count > 0){
         return self.deviceInfo.streamPtCidArray.count;
    }
    return 0;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    DevciceChartCell *cell = [tableView dequeueReusableCellWithIdentifier:[@"DevciceChartCell" description]];
    if(cell ==nil){
        cell = [[DevciceChartCell alloc]init];
    }
    [cell configViewWithEFADeviceInfoModel:self.deviceInfo indexPath:indexPath];
    return cell;
    
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return [tableView cellHeightForIndexPath:indexPath cellContentViewWidth:SCREEN_WIDTH tableView:tableView];
    //    return [tableView cellHeightForIndexPath: indexPath];
}

- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    cell.backgroundColor = [UIColor whiteColor];
}

//接受点击cell item项
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}


//刷新数据
- (void)refreshWholeView {
    [self.tableView reloadData];
}


#pragma mark - network request
- (void)requestDeviceChart{
    // 发布Cos需要登录
    if (![EFAModel sharedInstance].isLogin) {
        //        [[NSNotificationCenter defaultCenter] postNotificationName:KABGlobalNotiUserTokenInvalid object:nil];
        [self.tableView.mj_header endRefreshing];
        return;
    }
    
    NSDictionary *pars = @{@"efairyuser_id" : @([EFAModel sharedInstance].loginInfo.user_info.efairyuser_id),
                           @"access_token" : [EFAModel sharedInstance].loginInfo.access_token,
                           @"efairydevice_id" : @(self.deviceId),
                           @"start_time":_startDateLabel.text,
                           @"end_time":_endDateLabel.text
                           };
    MBProgressHUD *hud = [MBProgressHUD xd_showHUDAddedTo:self.view animated:YES];
    [[XDAFNetworking sharedInstance] GET:[ApiManager apiDeviceChart] parameters:pars progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        NSLog(@"请求设备信息返回：%@", responseObject);
        [hud hideAnimated:NO];
        //停止刷新头部
        [self.tableView.mj_header endRefreshing];
        self.deviceInfo = [EFADeviceInfoModel yy_modelWithDictionary:responseObject[EFAGlobalJsonKeyResult]];
        [self.deviceInfo unzipStreamList];
        [self refreshWholeView];
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        NSLog(@"请求设备信息失败：%@", error);
        //停止刷新头部
        [self.tableView.mj_header endRefreshing];
        NSString *msg = [[ApiErrorCode sharedInstance] errorCodeMsgWithError:error];
        [MBProgressHUD showPromptWithAutoHideInView:self.view message:msg];
    }];
}


-(void)setDefaultsDate{
    NSDate *currentdate = [NSDate date];
    //    NSTimeInterval  days = 24 * 60 * 60 * day;  //时长
    //    NSDate *newDate = [currentdate dateByAddingTimeInterval:24 * 60 * 60  * day];
    // 减去
    //    NSDate *newDate = [currentdate initWithTimeIntervalSinceNow: -days ];
    NSDateFormatter *formatter = [[NSDateFormatter alloc]init];
    [formatter setDateFormat:@"yyyy"];
    NSInteger currentYear = [[formatter stringFromDate:currentdate] integerValue];
    [formatter setDateFormat:@"MM"];
    NSInteger currentMonth = [[formatter stringFromDate:currentdate] integerValue];
    [formatter setDateFormat:@"dd"];
    NSInteger currentDay = [[formatter stringFromDate:currentdate] integerValue];
    [_startTimePickView setDefaultsDate:currentYear month:currentMonth day:currentDay];
    [_endTimePickView setDefaultsDate:currentYear month:currentMonth day:currentDay];
}

@end
